/******************************************************************************
 * Copyright 2022 The Airos Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "rsu_component.h"

#include "base/device_connect/rsu/device_factory.h"

namespace os {
namespace v2x {
namespace device {

bool AIROS_COMPONENT_CLASS_NAME(RSUComponent)::Init() {
  if (!LoadConfig(&conf_)) {
    AERROR << "load component proto config error" << std::endl;
    return false;
  }

  device_ = RSUDeviceFactory::Instance().GetUnique(
      conf_.device(),
      std::bind(&AIROS_COMPONENT_CLASS_NAME(RSUComponent)::CallBack, this,
                std::placeholders::_1));

  if (device_ == nullptr || !device_->Init(conf_.config_file())) {
    AERROR << "device_ init error";
    return false;
  }

  task_.reset(new std::thread([&]() { device_->Start(); }));

  return true;
}

bool AIROS_COMPONENT_CLASS_NAME(RSUComponent)::Proc(
    const std::shared_ptr<const os::v2x::device::RSUData>& recv_data) {
  device_->WriteToDevice(recv_data);
  return true;
}

void AIROS_COMPONENT_CLASS_NAME(RSUComponent)::CallBack(
    const RSUPBDataType& data) {
  Send("/v2x/device/rsu_out", data);
}

}  // namespace device
}  // namespace v2x
}  // namespace os